<?php

namespace App\Services\Admin;

use Illuminate\Support\Facades\Auth;
use App\Services\Service;
use App\Models\Notice;
use App\Models\User;
use App\Events\NoticeEvent;



class NoticeService extends Service
{

    public static function readAll(): array
    {

        $authUser = Auth::user();

        $user = User::find($authUser->id);

        // 先拿到所有未读通知 ID
        $unreadNoticeIds = $user->notices()
            ->wherePivot('is_read', 0)
            ->pluck('notices.id')
            ->toArray();
        // 标记为已读
        $user->notices()->updateExistingPivot(
            $unreadNoticeIds,
            ['is_read' => 1]
        );

        return [
            'id' => $user->id,
        ];
    }

    public static function read(string $id): array
    {

        $authUser = Auth::user();

        $user = User::find($authUser->id);

        $notice = $user->notices()->where('notices.id', $id)->first();

        if (!$notice) {
            self::throwValidationException('id', ['公告不存在']);
        }

        // 标记为已读
        $user->notices()->updateExistingPivot($id, ['is_read' => 1]);

        return $notice->toArray();
    }


    public static function myPage(array $params): array
    {

        $authUser = Auth::user();

        $user = User::find($authUser->id);

        $query = $user->notices()->orderBy('id', 'desc');

        $pageNum = $params['pageNum'];
        $pageSize = $params['pageSize'];
        $isRead = $params['isRead'] ?? null;

        if ($isRead !== null) {
            $query->wherePivot('is_read', $isRead);
        }

        $paginator = $query->paginate($pageSize, ['*'], 'page', $pageNum);

        $paginator->getCollection()->makeVisible(['createTime', 'updateTime']);

        return [
            'list'  => $paginator->items(),
            'total' => $paginator->total(),
        ];
    }


    public static function revoke(string $id): array
    {

        $notice = Notice::find($id);

        $userIds = $notice->users->pluck('id');

        foreach ($userIds as $item) {
            NoticeEvent::dispatch($item);
        }

        $notice->update([
            'publishStatus' => -1,
            'publishTime'   => null,
            'publishId'     => null,
            'revokeTime'    => now(),
        ]);

        // 同时删除关联的用户通知记录
        $notice->users()->detach();

        return [
            'id' => $notice->id,
        ];
    }


    public static function publish(string $id): array
    {

        $notice = Notice::find($id);

        $targetType = $notice->targetType;
        $targetUserIds = $notice->targetUserIds;

        // 2. 选择目标用户
        $userIds = $targetType == 1 ? User::pluck('id')->toArray() : $targetUserIds;

        $pivotData = collect($userIds)
            ->mapWithKeys(fn($uid) => [$uid => ['is_read' => 0]])
            ->toArray();

        $user = Auth::user();

        $notice->update([
            'publishStatus' => 1,
            'publishTime'   => now(),
            'publishId'     => $user->id,
            'revokeTime'    => null,
        ]);

        $notice->users()->syncWithoutDetaching($pivotData);

        foreach ($userIds as $item) {
            NoticeEvent::dispatch($item);
        }

        return [
            'id' => $notice->id,
        ];
    }


    public static function index(array $params): array
    {

        $query = Notice::query()->orderBy('id', 'desc');

        $pageNum = $params['pageNum'];
        $pageSize = $params['pageSize'];

        $paginator = $query->paginate($pageSize, ['*'], 'page', $pageNum);

        $paginator->getCollection()->makeVisible(['createTime', 'updateTime']);

        return [
            'list'  => $paginator->items(),
            'total' => $paginator->total(),
        ];
    }


    public static function store(array $data): array
    {

        $notice = Notice::create($data);

        return [
            'id' => $notice->id,
        ];
    }

    public static function show(string $id): array
    {

        $notice = Notice::find($id);

        if (!$notice) {
            self::throwValidationException('id', ['通知公告不存在']);
        }

        return $notice->toArray();
    }

    public static function update(array $data, string $id): array
    {

        $notice = Notice::find($id);

        if (!$notice) {
            self::throwValidationException('id', ['通知公告不存在']);
        }

        $notice->update($data);

        return [
            'id' => $notice->id,
        ];
    }

    public static function destroy(string $id): array
    {

        $notice = Notice::find($id);
        if (!$notice) {
            self::throwValidationException('id', ['通知公告不存在']);
        }

        $notice->delete();

        return [
            'id' => $notice->id
        ];
    }
}
